<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="168px">
      <el-form-item label="单据号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单据号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店" prop="shopId">
        <el-select
          v-model="queryParams.shopId"
          placeholder="全部"
          clearable
          :style="{width: '100%'}">
          <el-option
            v-for="(item, index) in shopList"
            :key="index"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户" prop="customerName">
        <el-select v-model="queryParams.customerId" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in customer" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作人" prop="createBy">
        <el-select v-model="queryParams.createBy" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.userName"
                     :value="item.userId" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" >
        <el-date-picker clearable
                        v-model="queryParams.createMinTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
        至
        <el-date-picker clearable
                        v-model="queryParams.createMaxTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核人" prop="approveBy">
        <el-select v-model="queryParams.approveBy" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.userName"
                     :value="item.userId" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核时间" >
        <el-date-picker clearable
                        v-model="queryParams.approveMinTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
        至
        <el-date-picker clearable
                        v-model="queryParams.approveMaxTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option label="待审核" value="0" ></el-option>
          <el-option label="审核通过" value="3" ></el-option>
          <el-option label="审核拒绝" value="6" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="销售员" prop="salerName">
        <el-select v-model="queryParams.salerName" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.userName"
                     :value="item.userId" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据号" align="left" prop="code" width="170"  show-overflow-tooltip/>
      <el-table-column label="门店名称" align="left" prop="shopName" />
      <el-table-column label="客户名称" align="left" prop="customerName" />
      <el-table-column label="销售员" align="left" prop="salerName" width="100"/>
      <el-table-column label="单据总金额" align="right" prop="totalAmount" width="100">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.totalAmount).toLocaleString() }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品数量" align="right" prop="totalNum" />
      <el-table-column label="操作时间" align="left" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="left" prop="createBy" width="100"/>
      <el-table-column label="状态" align="left" prop="status" >
        <template slot-scope="scope">
          <span>{{ scope.row.status == 0 ? "待审核" : scope.row.status == 3 ? "审核成功" : "审核拒绝"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="left" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="left" prop="approveBy" width="100"/>
      <el-table-column label="备注" align="left" prop="description" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="selectOrder(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
            v-if="scope.row.status != 3"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="statusUpdate(scope.row)"
            v-if="scope.row.status != 3"
          >审批</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
            v-if="scope.row.status != 3"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog id="printableArea" :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
        <div style="display: inline-block;width: 300px;"><p>门店：{{ this.form.shopName }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>客户：{{ this.form.customerName }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>销售员：{{ this.form.salerName }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>状态：<span :style="{color: statusColor}">{{ this.form.status==0 ? '待审核' : (this.form.status==3 ? '审核通过' : '审核拒绝') }}</span></p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.form.status == 6"><p>拒绝原因：{{ this.form.refuseReason }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>操作人：{{ this.form.createBy }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>操作时间：{{ parseTime(this.form.createTime, '{y}-{m}-{d}') }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;" v-if="this.form.approveBy"><p>审核人：{{ this.form.approveBy }}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.form.approveTime"><p>审核时间：{{ parseTime(this.form.approveTime, '{y}-{m}-{d}') }}</p></div>
        <br>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px">
        <el-table v-loading="loading" :data="tblSaleOrderDetailList" @selection-change="handleSelectionChange"  >
          <el-table-column label="商品编号" prop="baseDataProduct.code" align="center" width="100" show-overflow-tooltip/>
          <el-table-column label="商品名称" prop="baseDataProduct.name" align="center" width="150"/>
          <el-table-column label="单位" prop="baseDataProduct.unit" align="center" />
          <el-table-column label="规格" prop="baseDataProduct.spec" align="center" />
          <el-table-column label="商品类目" prop="baseDataProduct.baseDataProductCategory.name" align="center" />
          <el-table-column label="商品品牌" prop="baseDataProduct.baseDataProductBrand.name" align="center" />
<!--          <el-table-column label="参考销售价（元）" prop="oriPrice" align="center" width="130"/>-->
<!--          <el-table-column label="折扣（%）" prop="discountRate" align="center" width="100"/>-->
          <el-table-column label="价格（元）" prop="taxPrice" align="center" width="100"/>
          <el-table-column label="销售数量" prop="orderNum" align="center" />
          <el-table-column label="金额（元）" prop="amount" align="center" width="100">
            <template slot-scope="scope" v-if="scope.row.orderNum">
              <span>{{ Number((scope.row.taxPrice * scope.row.orderNum) - scope.row.taxPrice * scope.row.orderNum * (scope.row.taxRate / 100)).toLocaleString() }}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="含税金额" prop="taxAmount" align="center" >-->
<!--            <template slot-scope="scope">-->
<!--              <span>{{ Number(scope.row.taxPrice * scope.row.orderNum).toLocaleString() }}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="税率（%）" prop="taxRate" align="center" width="100"/>-->
          <el-table-column label="备注" prop="description" align="center" />
        </el-table>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
        <h3 style="margin:0 0 15px 10px;font-weight: bolder;">合计</h3>
        <div style="display: inline-block;margin-left:50px">
          销售数量：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled v-model="this.form.totalNum">
        </div>
        <div style="display: inline-block;margin-left:50px">
          含税总金额：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled v-model="this.form.totalAmount">
        </div>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
        <h3 style="margin:0 0 15px 10px;font-weight: bolder;margin-left: 10px">约定支付</h3>
        <el-form ref="form" :model="form" label-width="80px">
          <el-table :data="form.tblOrderPayTypeList" ref="tblPurchaseOrderDetail">
            <el-table-column label="支付方式" prop="payTypeId" width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.payTypeId" @keyup.enter.native="handleQuery" clearable disabled>
                  <el-option v-for="(item,index) in OrderPayTypeList" :key="index" :value="item.id" :label="item.name">{{item.name}}</el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="支付金额" prop="payAmount" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.payAmount" placeholder="请输入支付金额" disabled/>
              </template>
            </el-table-column>
            <el-table-column label="支付记录" prop="text" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.text" placeholder="" disabled/>
              </template>
            </el-table-column>
          </el-table>
          <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px;text-align: right">
            <label >备注： </label>
            <textarea style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid" v-model="this.form.description" disabled/>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="handlePrint" v-if="this.title == '查看'">打 印</el-button>
        <el-button type="success" @click="submitForm(3)" v-if="this.title == '审批' && this.form.status != 3">审核通过</el-button>
        <el-button type="danger" @click="submitForm(6)" v-if="this.title == '审批' && this.form.status != 6">审核拒绝</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="拒绝原因" :visible.sync="open2" width="500px" append-to-body>
      <el-form ref="refuseForm" :model="refuseReason" :rules="refuseRules" label-width="80px">
        <el-form-item label="拒绝原因" prop="refuseReason">
          <el-input type="textarea" v-model="refuseReason.refuseReason" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
        <el-button type="primary" @click="refuseSubmit">确 定</el-button>
        <el-button @click="statusCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, customer, center, updateOrder } from "@/api/system/order";
import { listUser } from "@/api/system/user";
import {left} from "core-js/internals/array-reduce";
import {parseTime} from "../../../utils/ruoyi";
import {listPayType}from "@/api/system/PayType";
import {listStock} from "@/api/system/stock";
import {listShop} from "../../../api/system/Shop";

export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售订单管理表格数据
      orderList: [],
      // 销售详情列表
      tblSaleOrderDetailList: [],
      // 销售数量
      orderNum: null,
      // 赠品数量
      giftNum: null,
      // 含税总金额
      taxAmount: null,
      // 拒绝原因
      refuseReason: {
        refuseReason: null
      },
      refuseRules: {
        refuseReason: [
          { required: true, message: "拒绝原因不能为空", trigger: "blur" }
        ]
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      //弹窗状态颜色
      statusColor:"rgb(100, 100, 100)",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        scId: null,
        customerId: null,
        createBy: null,
        createTime: null,
        createMinTime: null,
        createMaxTime: null,
        approveBy: null,
        approveTime: null,
        approveMinTime: null,
        approveMaxTime: null,
        status: null,
        salerName: null,
      },
      // 表单参数
      form: {},
      // 仓库下拉框
      ck: [],
      // 用户(审核人、操作人、销售员)下拉框
      user: [],
      // 客户下拉框
      customer: [],
      // 订单支付方式
      OrderPayTypeList: [],

      shopList: [], // 门店列表
    };
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,
    left,
    /** 查询销售订单管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.flag = null;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.reset()
      customer(this.customer).then(response => {
        this.customer = response.rows;
      });
      center({categoryType:1}).then(response => {
        this.ck = response.rows;
      });
      listUser(this.user).then(response => {
        this.user = response.rows;
      });
      listPayType().then(response => {
        this.OrderPayTypeList = response.rows;
        console.log(this.OrderPayTypeList)
      });
      listShop().then(response => {
        this.shopList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.getList();
    },
    // 审核拒绝取消按钮
    statusCancel() {
      this.open2=false;
      this.open=true;
    },
    //序号
    Index({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        scId: null,
        customerId: null,
        salerId: null,
        totalNum: null,
        totalGiftNum: null,
        totalAmount: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        approveBy: null,
        approveTime: null,
        status: null,
        refuseReason: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    getAmount(){
      this.getOrderNum();
      this.getGiftNum();
      this.getTaxAmount();
    },
    // 循环遍历，获取销售总数量
    getOrderNum() {
      let sum = 0;
      for (let i = 0; i < this.tblSaleOutSheetDetailList.length; i++) {
        sum += parseInt(this.tblSaleOutSheetDetailList[i].orderNum);
      }
      this.form.totalNum = sum;
    },
    // 循环遍历，获取赠品总数量
    getGiftNum() {
      let sum = 0;
      for (let i = 0; i < this.tblSaleOutSheetDetailList.length; i++) {
        if (this.tblSaleOutSheetDetailList[i].isGift == 1){
          sum += this.tblSaleOutSheetDetailList[i].orderNum;
        }
      }
      this.form.totalGiftNum = sum;
    },
    // 循环遍历，获取含税总金额
    getTaxAmount() {
      let sum = 0;
      for (let i = 0; i < this.tblSaleOutSheetDetailList.length; i++) {
        sum += this.tblSaleOutSheetDetailList[i].taxPrice * this.tblSaleOutSheetDetailList[i].orderNum;
      }
      this.form.totalAmount = sum;
    },
    // 查看按钮
    selectOrder(row) {
      if (row.status == 0) {
        this.statusColor = "rgb(100, 100, 100)";
      } else if (row.status == 3) {
        this.statusColor = "rgb(82, 196, 26)";
      } else {
        this.statusColor = "rgb(255, 0, 0)";
      }

      getOrder(row.id).then(response => {
        this.form = response.data;
        this.tblSaleOrderDetailList = response.data.tblSaleOrderDetailList;
        //根据仓库id和订单中的商品id，循环获取订单商品详情的库存数量
        for (let i = 0; i < this.tblSaleOrderDetailList.length; i++) {
          this.selectProductStockList(this.form.scId, this.tblSaleOrderDetailList[i])
        }
        this.open = true;
        this.title = "查看";
        console.log(this.tblSaleOrderDetailList);
      });
    },
    //获取库存列表
    selectProductStockList(scId, tblSaleOutSheetDetail) {
      listStock({scId,productId:tblSaleOutSheetDetail.productId}).then(response => {
        tblSaleOutSheetDetail.baseDataProduct.tblProductStock = response.rows[0];
      });
    },
    // 审批按钮
    statusUpdate(row){

      if (row.status == 0) {
        this.statusColor = "rgb(100, 100, 100)";
      } else if (row.status == 3) {
        this.statusColor = "rgb(82, 196, 26)";
      } else {
        this.statusColor = "rgb(255, 0, 0)";
      }

      getOrder(row.id).then(response => {
        this.form = response.data;
        this.tblSaleOrderDetailList = response.data.tblSaleOrderDetailList;
        //根据仓库id和订单中的商品id，循环获取订单商品详情的库存数量
        for (let i = 0; i < this.tblSaleOrderDetailList.length; i++) {
          this.selectProductStockList(this.form.scId, this.tblSaleOrderDetailList[i])
        }
        this.open = true;
        this.title = "审批";
        console.log(this.form);
      });
    },
    submitForm(status){
      for (let i = 0; i < this.tblSaleOrderDetailList.length; i++) {
        if (this.tblSaleOrderDetailList[i].baseDataProduct.tblProductStock.stockNum < this.tblSaleOrderDetailList[i].orderNum) {
          this.$modal.msgError("第" + (i + 1) + "行的销售数量大于库存数量，无法审核")
          return false;
        }
      }
      if (status==6){
        this.open = false;
        this.open2=true
      }else {
        this.form.status=status;
        this.form.approveBy='1';
        this.form.approveTime=new Date();
        this.$refs["form"].validate(valid => {
          if (valid) {
            updateOrder(this.form).then(response => {
              if(status==3){
                this.$modal.msgSuccess("审批成功");
              }else {
                this.$modal.msgError("审批拒绝")
              }
              this.open = false;
              this.getList();
            });
          }
        });
      }
    },
    //拒绝原因
    refuseSubmit() {
      this.$refs["refuseForm"].validate(valid => {
        if (valid) {
          this.form.status=6;
          this.form.approveBy='1';
          this.form.refuseReason=this.refuseReason.refuseReason;
          this.form.approveTime=new Date();
          updateOrder(this.form).then(response => {
            this.$modal.msgError("审批拒绝");
            this.open2 = false;
            this.open = false;
            this.getList();
          });
        }
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.open = true;
      // this.title = "添加销售订单管理";

      this.$router.push({
        path:'/order/add',
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      this.$router.push({
        path:'/order/update',
        query:{
          id: id,
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该销售订单？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    handlePrint() {
      window.print();
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 重新获取数据
      vm.getList();
    });
  }
};
</script>
